package com.solotiger.okex.oauth2;

import com.solotiger.okex.common.contants.GlobalContants;
import com.solotiger.okex.domain.OkexUser;
import com.solotiger.okex.domain.OkexUserToken;
import com.solotiger.okex.service.IShiroService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 认证
 * Author: Lin.Qiang
 * Date:2018/6/4 0004
 */
@Component
public class OAuth2Realm extends AuthorizingRealm {

    @Autowired
    private IShiroService shiroService;

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof OAuth2Token;
    }

    /**
     *  授权(验证权限时调用)
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        OkexUser user = (OkexUser)principalCollection.getPrimaryPrincipal();
        Integer userId = user.getUserId();
        System.out.println("userId = " + userId);
//        //用户权限列表
//        Set<String> permsSet = shiroService.findPermissionsByUserId(userId);

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
//        info.setStringPermissions(permsSet);
        return info;
    }

    /**
     * 认证(登录时调用)
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String accessToken = (String) authenticationToken.getPrincipal();
        //根据accessToken，查询用户信息
        OkexUserToken tokenEntity = shiroService.findByToken(accessToken);
        //token失效
        if(tokenEntity == null || tokenEntity.getExpireTime().getTime() < System.currentTimeMillis()){
            throw new IncorrectCredentialsException("invalid token");
        }

        //查询用户信息
        OkexUser user = shiroService.findUserById(tokenEntity.getUserId());
        //账号锁定
        if(user.getStatus() == GlobalContants.STATE_USER_DISABLE){
            throw new LockedAccountException("账号已被锁定,请联系管理员");
        }

        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, accessToken, getName());
        return info;
    }
}
